import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/SendGoods/MatureCarList.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../FandCar/SelectSourceOfGoods.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:platform/platform.dart';
class DesignatedDriver extends StatefulWidget {
  const DesignatedDriver({super.key, required this.orderId, required this.shipperId, required this.type});
 final String orderId;
  final String shipperId;
  //1普通指派 2取消并指派
  final int type;
  // final Map dataMap;
  @override
  State<DesignatedDriver> createState() => _DesignatedDriverState();
}

class _DesignatedDriverState extends State<DesignatedDriver> {
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  List dataList=[];
  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    super.initState();
    getLocCarListAction();
  }
  void  getLocCarListAction()async{
    List? Drivers=[];
    Drivers=await HisDriverPhoneManager.getDriverPhone();
    print(Drivers);
    if(Drivers!.isNotEmpty) {
      for (int i = 0; i < Drivers.length; i++) {
        NoLoadinggetApiManager.getData(
          context,
          "api/auth/driver/user/getUserByPhone",
          {'phoneNum':Drivers[i]},
              (responseData)  {
            setState(() {
            dataList.add(responseData['data']);

            });
          },
        );
      }
    }
  }
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }


 Future<void> reCommonWaybillAction(String drvId) async {
   String? token = await TokenManager.getToken();
   dio.interceptors.add(InterceptorsWrapper(
       onRequest: (options, handler) {
         options.headers["satoken"] = token;
         return handler.next(options);
       }
   ));
   dio.post(
     MyServiceUrl.header +
         'api/waybill/waybill/common/cancelWaybill',
     data: {
       "waybillId":widget.orderId,
       "cancelStatus":2,
       "drvId":drvId
     },
     options: Options(
       sendTimeout: Duration(seconds: 2),
       receiveTimeout: Duration(seconds: 50),
     ),
     onSendProgress: (a, b) => print('send ${a / b}'),
     onReceiveProgress: (a, b) =>
         print('received ${a / b}'),
   )
       .then((r) {
     setState(() {
       print(r);
       Map<String, dynamic> jsonMap = json.decode(
           r.toString());
       // 获取code和data
       String code = jsonMap['code'].toString();
       if (code == "200") {
         BrnToast.show("操作成功", context);
         Navigator.pop(context);

       } else {
         BrnToast.show(jsonMap['msg'], context);
       }
     });
   }).catchError((error) {
     print(error);
     ;
   });
 }
  void searchDriverAction(String drvPhoneNum,String vehicleNum) async {
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/auth/driver/user/getSearchUser', // 您的API端点key
      {"key":drvPhoneNum+vehicleNum}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          dataList=responseData['data'];
        });
      },
    );

  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("指派司机",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
        actions: [TextButton(onPressed: (){

        }, child: Text("微信指派",style: TextStyle(color: MyColors.themeColor),))],
      ),
      body: ListView(
        children: [
            Container(
              margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,),
              padding: EdgeInsets.only(left: 20.w,right: 10.w),
              decoration: BoxDecoration(
                  color: Color.fromRGBO(251, 236, 228, 1),
                  borderRadius: BorderRadius.all(Radius.circular(10))),
              height: 40.h,
              child:GestureDetector(
                child:    Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                Row(
                children: [
                Image.asset("lib/Images/OrderList/去指派熟车icon.png",width: 20.w,height: 20.h,),
                  SizedBox(width: 8.w,),
                  Text("去指派我的熟车",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,),),
                 ],
                      ),
                    Icon(Icons.arrow_forward_ios,color: MyColors.themeColor,),
                  ],
                ),
                  onTap: (){
                    Navigator.push( context, FadeRoute(page:MatureCarList(
                      orderId: widget.orderId, shipperId: widget.shipperId,
                    )));

                  },
              ),

            ),
          Container(
            height: 50.h,
            child: BrnSearchText(
              autoFocus:false,
              focusNode: focusNode,
              controller: textController,
              searchController: scontroller..isActionShow = false,
              outSideColor:MyColors.backgreyColor,
              innerColor:Colors.white,
              borderRadius:BorderRadius.all(const Radius.circular(10.0)),
              hintText:"输入司机手机号码/车牌号",
              onTextClear: () {
                debugPrint('sss');
                return false;
              },
              onActionTap: () {
                scontroller.isClearShow = false;
                scontroller.isActionShow = false;
                focusNode.unfocus();

              },
              onTextCommit: (text) {

              },
              onTextChange: (text) {
                if(text!="") {
                  if (text.contains(RegExp(r'[a-zA-Z]')) && text.length > 0) {
                    searchDriverAction(text, "");
                  } else {
                    searchDriverAction("", text);
                  }
                }
              },
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 15.w),
            child:  Text("此列表仅显示最近交易过的司机",style: TextStyle(color: MyColors.hintColor,fontSize: 12.sp),),
          ),

          Container(
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,),
            height: screenSize.height-230.h,
            child: ListView.builder(
                shrinkWrap:false,
                itemCount:dataList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    decoration: BoxDecoration(
                        color:Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    // margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,),
                    padding: EdgeInsets.all(15.w),
                    margin: EdgeInsets.only(bottom: 8.h),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                  width: 36.w,
                                  height: 36.h,
                                  child:  dataList[index]['avatarPath']!=null&&dataList[index]['avatarPath']!=""?
                                  CircleAvatar(
                                    radius: 15,
                                    backgroundImage: NetworkImage(MyServiceUrl.imgHeader +dataList[index]['avatarPath']),
                                  )
                                      :  CircleAvatar(
                                    radius: 15,
                                    backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                                  ),
                                ),


                                    SizedBox(width: 8.w,),
                                    Text(dataList[index]['realName'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 16.sp),),
                              ],
                            ),

                            // BrnTagCustom.buildBorderTag(
                            //   tagText: dataList[index]['qualificationCertificateStatus']!=2?'三证齐全':'五证齐全',
                            //   textColor: MyColors.themeColor,
                            //   borderColor: MyColors.themeColor,
                            //   borderWidth: 1.w,
                            //   fontSize: 11.sp,
                            // )
                          ],
                        ),
                        SizedBox(height: 8.h,),
                        Text(dataList[index]['vehicleNum'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 16.sp)),
                        SizedBox(height:4.h,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [

                                Container(
                                  width: 180.w,
                                  child:  Text(dataList[index]['vehicleLength'].toString()+"丨"+dataList[index]['vehicleModel'].toString()+"  "+dataList[index]['vehicleTonnage'].toString()+"吨",style: TextStyle(overflow:  TextOverflow.ellipsis,color: MyColors.textColor,fontSize: 13.sp),)

                                )
                              ],
                            ),
                            RichText(
                              text: TextSpan(
                                text: '好评率 ', // 第一部分文本
                                style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),
                                children: [
                                  TextSpan(
                                    text:dataList[index]['rating']!=null? dataList[index]['rating'].toString()+"%":"--"+'%', // 第二部分文本
                                    style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        Divider(
                          height: 16.h,
                          color: MyColors.backgreyColor,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                              child: Image.asset("lib/Images/OrderList/IMicon.png",width: 25.w,height: 25.h,),
                              onTap: (){

                              },
                            ),
                            Row(
                              children: [
                                BrnSmallOutlineButton(
                                  width: 60.w,
                                  radius:30,
                                  title: '联系他',
                                  textColor: MyColors.themeColor,
                                  lineColor: MyColors.themeColor,
                                  onTap: () {
                                    _makePhoneCall(dataList[index]['phoneNum']);
                                  },
                                ),
                                SizedBox(width: 4.w,),
                                BrnSmallMainButton(
                                  title: '指定承运',
                                  bgColor: MyColors.themeColor,
                                  textColor: Colors.white,
                                  radius:30,
                                  onTap: () {
                                    showDialog(
                                      barrierDismissible: false,
                                      context: context,
                                      builder: (BuildContext context) {
                                        return BrnDialog(

                                          titleText: "是否确认指派司机？",
                                          actionsWidget: [
                                            TextButton(
                                              onPressed: () {
                                                Navigator.pop(context);
                                              },
                                              child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                            ),
                                            TextButton(

                                              onPressed: () {
                                                print(dataList[index]['driverId']);
                                                ApiManager.postData(
                                                  context,
                                                  'api/waybill/shipper/waybill/add',
                                                  {
                                                    "goodsId":widget.orderId,
                                                    "driverId":dataList[index]['driverId'],
                                                  },
                                                      (responseData) {
                                                    BrnToast.show("指派成功", context);

                                                    Navigator.pop(context);
                                                    Navigator.pop(context);
                                                  },
                                                );


                                              },
                                              child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                            ),
                                          ],
                                        );
                                      },
                                    );
                                      // Navigator.push( context, FadeRoute(page:SelectSourceOfGoods(carMap:dataList[index],)));


                                  },
                                )
                              ],
                            ),
                          ],
                        )
                      ],
                    ),
                  );
                }),
          )
        ],
      ),
    );
  }
}
